<?php
/*
 * Copyright 2007 Bjørn Tore Håvie
 * 
 * This file is part of ITSBOT.
 * 
 * ITSBOT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ITSBOT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ITSBOT.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @package ITSBOT
 * @subpackage Timing
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Timer{
	
	private $funcs;
	
	private static $inst;
	
	/**
	 * Get the instance of the timer
	 *
	 * @return Timer
	 */
	public static function Get(){
		if(Timer::$inst)
			return Timer::$inst;
		return Timer::$inst = new Timer();
	}
	
	private function __construct(){
		
	}
	
	public function Wait($max = 0, $min = 0){
		$next = isset($this->funcs[0])? $this->funcs[0] : false;
		$time = $next['time'] - $this->Time();
		$smax = ($max)? min($time, $max) : $time;
		if(!$next) $smax = $max;
		sleep($smax);
		if($smax != $time)
			return false;
		call_user_func_array($this->funcs[0]['func'], $this->funcs[0]['data']);
		array_shift($this->funcs);
		//$this->Sort();
		return true;
	}
	
	/**
	 * Add a new entry to the timer
	 *
	 * @param callback $func The callback
	 * @param int $time The time to wait, in seconds
	 * @param mixed $data Additional data to pass to the callback
	 */
	public function Add($func, $time, $data = null){
		$this->funcs[] = array('func' => $func, 'time' => $time + $this->Time(), 'data' => $data);
		$this->Sort();
	}
	
	private function Time(){
		return time();
	}
	
	private function Sort(){
		usort($this->funcs, array('Timer', 'Compare'));
	}
	
	public static function Compare($a, $b){
		if($a['time'] == $b['time'])
			return 0;
		return ($a['time'] > $b['time'])? 1 : -1;
	}
}
?>